package com.xakcop.p4reviewboard.prefs;

import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.FileFieldEditor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

import com.xakcop.p4reviewboard.Activator;

public class PreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {

  public static final String POST_REVIEW_EXECUTABLE = "postReview.executable";
  public static final String POST_REVIEW_ARGUMENTS = "postReview.arguments";
  public static final String POST_REVIEW_USERNAME = "postReview.username";
  public static final String POST_REVIEW_PASSWORD = "postReview.password";
  public static final String PASS_ARGS_ON_LAUNCH = "passArgumentsOnLaunch";

  public static final String REVIEWBOARD_URL = "reviewBoard.url";
  public static final String REPOSITORY = "reviewBoard.repository";

  public PreferencePage() {
    super(GRID);
  }

  @Override
  protected void createFieldEditors() {
    addField(new StringFieldEditor(REVIEWBOARD_URL, "Server url:",
        50, getFieldEditorParent()));
    addField(new StringFieldEditor(REPOSITORY, "Repository:",
        50, getFieldEditorParent()));
    addField(new FileFieldEditor(POST_REVIEW_EXECUTABLE, "Post-review executable:",
        true, getFieldEditorParent()));
    addField(new StringFieldEditor(POST_REVIEW_USERNAME, "Username:",
        30, getFieldEditorParent()));
    addField(new PasswordFieldEditor(POST_REVIEW_PASSWORD, "Password:",
        30, getFieldEditorParent()));
    addField(new StringFieldEditor(POST_REVIEW_ARGUMENTS, "Additional arguments (optional):",
        50, getFieldEditorParent()));
    addField(new BooleanFieldEditor(PASS_ARGS_ON_LAUNCH, "Review command line arguments on launch",
        SWT.NONE, getFieldEditorParent()));
  }

  @Override
  protected IPreferenceStore doGetPreferenceStore() {
    return Activator.getDefault().getPreferenceStore();
  }

  public void init(IWorkbench workbench) {
  }

  /**
   * Our little extension to support password field editing.
   */
  private static class PasswordFieldEditor extends StringFieldEditor {

    public PasswordFieldEditor(String name, String labelText, int width, Composite parent) {
      super(name, labelText, width, parent);
    }

    @Override
    public Text getTextControl(Composite parent) {
      Text text = super.getTextControl(parent);
      text.setEchoChar('*');
      return text;
    }
  }
}
